package com.rhino.xchat.constant

import com.blankj.utilcode.util.SPUtils
import com.rhino.base.utils.GsonUtils
import com.rhino.base.webview.WebViewConfig
import com.rhino.xchat.http.response.ResLoginInfo
import com.rhino.xchat.http.response.ResUserInfo
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch


/**
 * @author LuoLin
 * @since Create on 2025/4/1.
 */
object Cache {

    val spAccount: SPUtils by lazy {
        SPUtils.getInstance("account")
    }

    val spConfig: SPUtils by lazy {
        SPUtils.getInstance("config")
    }

    val spCommon: SPUtils by lazy {
        SPUtils.getInstance("common")
    }

    private var loginInfo: ResLoginInfo? = null
    private var userInfo: ResUserInfo? = null

    fun logout() {
        loginInfo = null
        userInfo = null
        spAccount.clear(true)
    }

    fun clearAll() {
        logout()
        spConfig.clear(true)
        spCommon.clear(true)
    }

    fun clearAllUserInfo() {
        logout()
        spAccount.clear(true)
    }

    fun hasLogin(): Boolean {
        return !getLoginInfo()?.getAccessToken().isNullOrEmpty()
    }

    fun getLoginInfo(): ResLoginInfo? {
        if (loginInfo == null) {
            loginInfo =
                GsonUtils.fromJson(spAccount.getString("loginInfo"), ResLoginInfo::class.java)
        }
        return loginInfo
    }

    fun saveLoginInfo(loginInfo: ResLoginInfo?) {
        this.loginInfo = loginInfo
        spAccount.put("loginInfo", GsonUtils.toJson(loginInfo))
    }

    fun getUserId(): String {
        return getUserInfo()?.id ?: ""
    }

    fun getUserName(): String {
        return getUserInfo()?.name ?: ""
    }

    fun getUserInfo(): ResUserInfo? {
        if (userInfo == null) {
            userInfo = GsonUtils.fromJson(spAccount.getString("userInfo"), ResUserInfo::class.java)
        }
        return userInfo
    }

    fun saveUserInfo(userInfo: ResUserInfo?) {
        this.userInfo = userInfo
        MainScope().launch(Dispatchers.IO) {
            spAccount.put("userInfo", GsonUtils.toJson(userInfo))
        }
    }
}